//
//  FindPwdViewController.m
//  UESTCPioneer
//
//  Created by Apple on 14-6-22.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "FindPwdViewController.h"

@interface FindPwdViewController ()
{
    UIButton * findPwd;
    UILabel  * showPwd;
    UITextField * textField;
}
@end

@implementation FindPwdViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad]; /*inputkuang.png*/
    // Do any additional setup after loading the view.
    
    
    UILabel * infoLabel = [[UILabel alloc] init];
    [self.view addSubview:infoLabel];
    [infoLabel setText:@"请输入身份证号:"];
    infoLabel.textAlignment = NSTextAlignmentLeft;
    [infoLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:infoLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:10]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:infoLabel attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:10]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:infoLabel attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1 constant:-10]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[infoLabel(==40)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(infoLabel)]];
    /*
    [backgroundImageView.layer setCornerRadius:5];
    [backgroundImageView.layer setBorderWidth:1];
    [backgroundImageView.layer setBorderColor:[UIColor colorWithWhite:146.0/255.0 alpha:0.5].CGColor];
    */
    
    textField = [[UITextField alloc] init];
    [self.view addSubview:textField];
    [textField.layer setCornerRadius:5];
    [textField.layer setBorderWidth:1];
    [textField.layer setBorderColor:[UIColor colorWithWhite:146.0/255.0 alpha:0.5].CGColor];
//    textField.borderStyle = UITextBorderStyleLine;
    [textField setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:textField attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:infoLabel attribute:NSLayoutAttributeBottom multiplier:1 constant:10]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:textField attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:infoLabel attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:textField attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:infoLabel attribute:NSLayoutAttributeRight multiplier:1 constant:0]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[textField(==40)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(textField)]];
    
    
//    //背景
//    UIImageView *backgroundImageView = [[UIImageView alloc]init];
//    //        [backgroundImageView setImage:[UIImage imageNamed:@"inputkuang"]];
//    [self.view addSubview:backgroundImageView];
//    [backgroundImageView.layer setCornerRadius:5];
//    [backgroundImageView.layer setBorderWidth:1];
//    [backgroundImageView.layer setBorderColor:[UIColor colorWithWhite:146.0/255.0 alpha:0.5].CGColor];
//    
//    //        [backgroundImageView setContentMode:UIViewContentModeRedraw];
//    [backgroundImageView setTranslatesAutoresizingMaskIntoConstraints:NO];
//    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[backgroundImageView]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(backgroundImageView)]];
//    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[backgroundImageView]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(backgroundImageView)]];
//    [textField setTranslatesAutoresizingMaskIntoConstraints:NO];
//    
//    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:backgroundImageView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:infoLabel attribute:NSLayoutAttributeBottom multiplier:1 constant:10]];
//    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:backgroundImageView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:infoLabel attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];
//    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:backgroundImageView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:infoLabel attribute:NSLayoutAttributeRight multiplier:1 constant:0]];
//    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[textField(==40)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(textField)]];
    
    
    
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ScreenTouch)];
    [self.view addGestureRecognizer:tapGesture];
    [self showFindPwdBtn];
}

-(void)showPwdLabel:(NSString *)password{

    showPwd = [[UILabel alloc] init];
    [self.view addSubview: showPwd];
    showPwd.text = password;
    [showPwd setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:showPwd attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:textField attribute:NSLayoutAttributeBottom multiplier:1 constant:10]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:showPwd attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:textField attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:showPwd attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:textField attribute:NSLayoutAttributeRight multiplier:1 constant:0]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[showPwd(==40)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(showPwd)]];
}
-(void)hideShowPwd{
    [showPwd removeFromSuperview];
}

-(void)showFindPwdBtn{

    findPwd = [[UIButton alloc]init];
    [findPwd setTitle:@"确定" forState:UIControlStateNormal];
    [findPwd setTitle:@"确定" forState:UIControlStateHighlighted];
    [findPwd setTitle:@"确定" forState:UIControlStateSelected];
    [findPwd.layer setCornerRadius:5];
    [findPwd.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [findPwd setBackgroundColor:kNavigationBarColor];
    [findPwd setShowsTouchWhenHighlighted:YES];
    [findPwd setTranslatesAutoresizingMaskIntoConstraints:NO];
    [findPwd setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    
    [findPwd addTarget:self action:@selector(findPassword:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:findPwd];
    [findPwd setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:findPwd attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:textField attribute:NSLayoutAttributeBottom multiplier:1 constant:10]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:findPwd attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:textField attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:findPwd attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:textField attribute:NSLayoutAttributeRight multiplier:1 constant:0]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[findPwd(==40)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(findPwd)]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[findPwd(==150)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(findPwd)]];


}

-(void)hideFindPwdBtn{
    [findPwd removeFromSuperview];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}

-(void)ScreenTouch{

    [textField resignFirstResponder];
}

#pragma mark 找回密码
-(void)findPassword:(UIButton *)btn{
    BOOL result = [self identifyNumCheck:textField.text];
    if (!result) {
        return;
    }
    NSDictionary *requestData=@{
                                @"type":@"codeBack"
                                ,@"sfz":textField.text
                                };
    
    [NetworkCenter AFRequestWithData:requestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
//        NSLog(@"arr = %@",arr);
//        NSDictionary *dic =arr[0];
        if ([dic[@"result"] isEqualToString:@"fail"]){
            [Alert showAlert:@"身份证信息有误!"];
            return ;
        }
        else {
            [self hideFindPwdBtn];
            [self showPwdLabel:[NSString stringWithFormat:@"您的密码是 : %@",dic[@"result"]]];
        }
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Alert showAlert:@"网络请求发生错误"];
    }];

    
    

}

-(BOOL)identifyNumCheck:(NSString*) identifyNum{
    if (identifyNum.length == 15 || identifyNum.length == 18) {
        NSString *emailRegex = @"^[0-9]*$";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
        bool sfzNo = [emailTest evaluateWithObject:[identifyNum stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
        
        if (identifyNum.length == 15) {
            if (!sfzNo) {
                //                [self HUDShow:@"请输入正确的身份证号" delay:1.5];
                [Alert showAlert:@"身份证号格式有误"];
                return NO;
            }
        }else if (identifyNum.length == 18) {
            bool sfz18NO = [self checkIdentityCardNo:identifyNum];
            if (!sfz18NO) {
                //                [self HUDShow:@"请输入正确的身份证号" delay:1.5];
                [Alert showAlert:@"身份证号格式有误"];
                return NO;
            }
        }
        return YES;
    }else{
        [Alert showAlert:@"身份证号格式有误"];
        return NO;
    }
}
#pragma mark - 身份证识别
-(BOOL)checkIdentityCardNo:(NSString*)cardNo
{
    if (cardNo.length != 18) {
        return  NO;
    }
    NSArray* codeArray = [NSArray arrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2", nil];
    NSDictionary* checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil]  forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]];
    
    NSScanner* scan = [NSScanner scannerWithString:[cardNo substringToIndex:17]];
    
    int val;
    BOOL isNum = [scan scanInt:&val] && [scan isAtEnd];
    if (!isNum) {
        return NO;
    }
    int sumValue = 0;
    
    for (int i =0; i<17; i++) {
        sumValue+=[[cardNo substringWithRange:NSMakeRange(i , 1) ] intValue]* [[codeArray objectAtIndex:i] intValue];
    }
    
    NSString* strlast = [checkCodeDic objectForKey:[NSString stringWithFormat:@"%d",sumValue%11]];
    
    if ([strlast isEqualToString: [[cardNo substringWithRange:NSMakeRange(17, 1)]uppercaseString]]) {
        return YES;
    }
    
    return  NO;
}

@end
